<template>
  <div>
    <a-modal :visible="visible" @before-open="open" :on-before-ok="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" width="800px" top="20%" :mask-closable="false">
      <template #title> {{ title }} </template>
      <template #footer>
        <a-button class="gray-outline" @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="submitLoading" @click="handleOk">确定</a-button>
      </template>
      <div>
        <a-form auto-label-width ref="formRef" size="medium" :model="form">
          <a-space direction="vertical" :size="24">
            <a-row>
              <a-col :span="8">
                <a-form-item field="sort" label="排序">
                  <a-input-number hide-button v-model="form.sort" placeholder="请输入" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="name" label="属性中文名称" :rules="rules.name">
                  <a-input v-model="form.name" placeholder="请输入" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="nameEn" label="属性英文名称" :rules="rules.nameEn">
                  <a-input v-model="form.nameEn" placeholder="请输入" allow-clear />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-item field="propGroupId" label="属性分组" :rules="rules.propGroupId">
                  <a-select v-model="form.propGroupId" allow-clear placeholder="请选择">
                    <a-option v-for="item of groupOptions" :label="item.name" :value="item.id"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="type" label="属性值类型" :rules="rules.type">
                  <a-select v-model="form.type" allow-clear placeholder="请选择">
                    <a-option v-for="item of typeOptions" :label="item.label" :value="item.value"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="txtLength" label="文本长度" :rules="[{ required: true, message: '请输入属性值' }]" v-if="form.type == '4'">
                  <a-input v-model="form.txtLength" placeholder="请输入长度" allow-clear></a-input>
                </a-form-item>
                <a-form-item field="unit" label="单位" :rules="rules.unit" v-if="[5, 6, 7, 8].includes(form.type)">
                  <a-select v-model="form.unit" allow-clear placeholder="请选择">
                    <a-option v-for="item of unitList" :label="item.name" :value="item.name"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-item field="status" label="状态">
                  <a-switch v-model="form.status"></a-switch>
                </a-form-item>
              </a-col>
            </a-row>
          </a-space>
        </a-form>
      </div>
      <div class="dyna-table" v-if="form.type == '1' || form.type == '2'">
        <div class="title">基础信息</div>

        <a-table class="table-singe-line" size="mini" :data="form.propValueList" @change="handleChange" :pagination="false" :scroll="{ y: 300 }" :draggable="{ type: 'handle', width: 30 }">
          <template #columns>
            <a-table-column v-for="item of columns" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
              <!-- <template v-if="item.title == '序号'" #cell="{ record, rowIndex }">
                {{ rowIndex + 1 }}
              </template> -->
              <template v-if="item.title == '属性值'" #cell="{ record }">
                <a-input v-model="record.propValue" allow-clear placeholder="请输入"></a-input>
              </template>
              <template v-else-if="item.title == '属性值英文'" #cell="{ record }">
                <a-input v-model="record.propValueEn" allow-clear placeholder="请输入"></a-input>
              </template>
              <template v-else="item.title == '操作'" #cell="{ record, rowIndex }">
                <div style="width: 100%">
                  <!-- <template #drag-handle-icon>
                    <icon-drag-arrow class="icon" />
                  </template> -->
                  <!-- <icon-drag-arrow class="icon" /> -->
                  <icon-plus-circle class="icon" style="margin: 0 10px" @click="form.propValueList.push({ propValue: '', propValueEn: '' })" />
                  <icon-minus-circle class="icon" @click="delPropItem(record, rowIndex)" v-if="rowIndex != 0" />
                </div>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, computed, reactive } from 'vue'
  import { addPropsType } from '../type'
  import { Message, Modal } from '@arco-design/web-vue'
  import { updateRelatedList, getPropertyGroupList, isPropertyNameExist, getUnitList } from '@/api/product'
  import _ from 'lodash-es'

  const typeOptions = [
    { label: '单选', value: 1 },
    { label: '多选', value: 2 },
    { label: '是/否', value: 3 },
    { label: '文本', value: 4 },
    { label: '数字(整数)', value: 5 },
    { label: '数字(小数)', value: 6 },
    { label: '三维', value: 7 },
    { label: '二维', value: 8 },
  ]

  const columns: any = [
    {
      title: '属性值',
      dataIndex: 'chinese',
      align: 'left',
      width: 150,
    },
    {
      title: '属性值英文',
      dataIndex: 'english',
      align: 'left',
      width: 150,
    },
    {
      title: '操作',
      align: 'left',
      width: 60,
    },
  ]

  export default defineComponent({
    name: 'addCateGory',
    emits: ['save'],
    props: ['detail'],
    setup(props: addPropsType, { emit }) {
      let visible = ref(false)
      let groupOptions: any = ref([])
      let unitList: any = ref([])
      let submitLoading = ref(false)
      let form: any = ref({
        sort: '',
        source: 'custom',
        name: '',
        nameEn: '',
        propGroupId: '',
        delPropValueIdList: [],
        propValueList: [{ propValue: '', propValueEn: '' }],
        type: '',
        unit: '',
        txtLength: '',
        status: true,
      })
      const formRef = ref()
      const rules = {
        name: [{ required: true, message: '请输入属性中文名称' }],
        nameEn: [{ required: true, message: '请输入属性英文名称' }],
        propGroupId: [{ required: true, message: '请选择分组' }],
        type: [{ required: true, message: '请选择类型' }],
        unit: [{ required: true, message: '请选择单位' }],
      }

      const handleOk = () => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            if (form.value.type == '1' || form.value.type == '2') {
              for (let i = 0; i < form.value.propValueList.length; i++) {
                const element = form.value.propValueList[i]
                if (!element.propValue) {
                  return Message.error(`序号为${i + 1}的属性值为必填项`)
                }
              }
            }
            let params = form.value
            if (params.type != 1 && params.type != 2) {
              delete params.propValueList
            }

            // 校验名称是否重复
            const result: any = await isPropertyNameExist({ name: params.name })
            if (result.data && props.detail.type == 'add') {
              Modal.error({
                title: '提示',
                content: '系统中已经存在相同属性名，是否继续创建',
                titleAlign: 'start',
                cancelText: '取消',
                hideCancel: false,
                onBeforeOk: async (done) => {
                  done(true)
                  add(params)
                },
              })
            } else {
              add(params)
            }
          }
        })
      }

      const add = async (params: any) => {
        submitLoading.value = true
        const res: any = await updateRelatedList(params)
        if (res.code == 'SUCCESS') {
          form.value = {
            sort: '',
            source: 'custom',
            name: '',
            nameEn: '',
            propGroupId: '',
            delPropValueIdList: [],
            propValueList: [{ propValue: '', propValueEn: '' }],
            type: '',
            unit: '',
            txtLength: '',
            status: true,
          }
          props.detail.type == 'add' ? Message.success('添加成功') : Message.success('编辑成功')
          visible.value = false
          submitLoading.value = false

          emit('save')
        }
      }

      const handleCancel = () => {
        formRef.value.resetFields()
        submitLoading.value = false
        visible.value = false
      }

      const title = computed(() => {
        if (props.detail.type == 'add') {
          return '新增属性'
        } else {
          return '编辑属性'
        }
      })

      const delPropItem = (item: any, index: any) => {
        if (item.id) {
          form.value.delPropValueIdList.push(item.id)
        }
        form.value.propValueList.splice(index, 1)
      }

      const handleChange = (val: any) => {
        form.value.propValueList = val
      }

      // 获取属性分组
      const getGroupList = async () => {
        const res: any = await getPropertyGroupList()
        groupOptions.value = res.data
      }

      // 获取单位列表数据
      const getUnit = async () => {
        let params = {
          pageNum: 1,
          pageSize: 9999,
        }
        const res = await getUnitList(params)
        unitList.value = res?.data?.records
      }
      const open = () => {
        getGroupList()
        getUnit()
        if (props.detail.type == 'edit') {
          form.value = _.cloneDeep(props.detail.data)
          if (form.value.propValueList.length <= 0) {
            form.value.propValueList = [{ propValue: '', propValueEn: '' }]
          }
          form.value.delPropValueIdList = []
        } else {
          form.value = {
            sort: '',
            source: 'custom',
            name: '',
            nameEn: '',
            propGroupId: '',
            delPropValueIdList: [],
            propValueList: [{ propValue: '', propValueEn: '' }],
            type: '',
            unit: '',
            txtLength: '',
            status: true,
          }
        }
      }

      return { visible, open, unitList, submitLoading, handleOk, handleCancel, delPropItem, title, form, rules, formRef, groupOptions, typeOptions, columns, handleChange }
    },
  })
</script>

<style lang="less" scoped>
  .icon {
    color: #2b65ef;
    font-size: 20px;
  }
  .dyna-table {
    // padding: 10px 20px;
    box-sizing: border-box;
    .title {
      font-size: 16px;
      height: 18px;
      line-height: 18px;
      margin-bottom: 20px;
      &::before {
        content: '';
        display: inline-block;
        width: 6px;
        height: 18px;
        background-color: #2561ef;
        float: left;
        margin-right: 5px;
        border-radius: 3px;
      }
      &::after {
        content: '';
        display: inline-block;
        width: calc(100% - 80px);
        margin: -9px 0 0 81px;
        border-top: 1px solid #f2f2f2;
        float: left;
      }
    }
  }
</style>
